import { getLs } from '@/common/common'
import React, { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'

export default function useSocketHook() {
    const {_id} = getLs("userInfo")
    const [socketInstance, setSocketInstance] = useState(null) // 保存 WebSocket 实例
    const dispatch = useDispatch()
    useEffect(() => {
        if(_id){
            connectSocket()
        }
        return ()=>{
            if (socketInstance) {
                socketInstance.close() // 清理连接
              }
        }
    }, [_id])
    const connectSocket = ()=>{
        // 建立socket连接
        const socket  = new WebSocket(`ws://127.0.0.1:5000?id=${_id}`);
        // 监听 WebSocket 连接打开事件
        socket.onopen = () => {
            socket.send('前端打开连接');  // 向服务器发送消息
        };
        // 监听服务器消息
        socket.onmessage = (e) => {
            if (e.data) {
                const info = JSON.parse(e.data)
                if (Boolean(info?.messageType)) {
                    updateNumber(info)
                }
            }
        };
        socket.onclose = () => {
            console.log("重连中.....");
            setTimeout(connectSocket, 1000) // 1秒后重新连接
        };
        
        setSocketInstance(socket)
    }
    const updateNumber = (socketMessage) => {
        dispatch({ type: socketMessage.messageType, payload: 1 })
    }
  return {
    _id
}
}
